package com.wechatapp.mengyao.poetry.service.impl;

import com.wechatapp.mengyao.poetry.core.CurrentContext;
import com.wechatapp.mengyao.poetry.core.JwtUtils;
import com.wechatapp.mengyao.poetry.core.OperatingUser;
import com.wechatapp.mengyao.poetry.core.WeChatHelper;
import com.wechatapp.mengyao.poetry.dto.*;
import com.wechatapp.mengyao.poetry.entity.SocialAuth;
import com.wechatapp.mengyao.poetry.entity.UserInfo;
import com.wechatapp.mengyao.poetry.exception.InvalidTokenException;
import com.wechatapp.mengyao.poetry.mapper.SocialAuthMapper;
import com.wechatapp.mengyao.poetry.mapper.UserInfoMapper;
import com.wechatapp.mengyao.poetry.service.UserInfoService;
import com.wechatapp.mengyao.poetry.vo.LoginResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * @author yanghuaxu
 * @date 2025/5/20 17:29
 */
@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SocialAuthMapper socialAuthMapper;
    @Autowired
    private WeChatHelper weChatHelper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public LoginResponse login(LoginRequestDTO loginRequestDTO) {
        UserInfoDTO userInfo = loginRequestDTO.getUserInfo();
        WeChatInfo weChatInfo = weChatHelper.parseWeChatInfo(loginRequestDTO);
        userInfo.setOpenId(weChatInfo.getOpenId());
        userInfo.setUnionId(weChatInfo.getUnionId());
        UserInfo existUser = getUserByPlatformAndId(userInfo.getPlatform(), userInfo.getOpenId());
        if (existUser == null) {
            log.info("用户不存在，新建用户");
            existUser = createUser(userInfo);
        } else {
            log.info("用户已存在，返回用户信息");
            existUser.setUpdateTime(new Date());
            userInfoMapper.updateByPrimaryKeySelective(existUser);
        }
        return new LoginResponse(existUser, JwtUtils.generateToken(userInfo.getOpenId(), userInfo.getUnionId()));
    }

    @Override
    public UserInfo getUserByPlatformAndId(String platform, String openId) {
        return userInfoMapper.getUserByPlatformAndId(platform, openId);
    }

    @Override
    public UserInfo createUser(UserInfoDTO userInfo) {
        UserInfo newUser = new UserInfo();
        newUser.setNickname(userInfo.getNickname());
        newUser.setAvatarUrl(userInfo.getAvatarUrl());
        newUser.setGender(userInfo.getGender());
        newUser.setProvince(userInfo.getProvince());
        newUser.setCity(userInfo.getCity());
        newUser.setCountry(userInfo.getCountry());
        newUser.setEmail(userInfo.getEmail());
        newUser.setCreateTime(new Date());
        userInfoMapper.insertSelective(newUser);
        SocialAuth auth = new SocialAuth();
        auth.setOpenid(userInfo.getOpenId());
        auth.setUnionid(userInfo.getUnionId());
        auth.setPlatform(userInfo.getPlatform());
        auth.setUserId(newUser.getId());
        auth.setCreateTime(new Date());
        socialAuthMapper.insertSelective(auth);
        return newUser;
    }

    @Override
    public UserInfo updateUser(UserInfoDTO userInfoDTO) {
        log.info("开始更新微信用户信息");
        UserInfo currentUser = userInfoMapper.selectByPrimaryKey(userInfoDTO.getId());
        if (ObjectUtils.isEmpty(currentUser)) {
            currentUser = userInfoMapper.getUserByPlatformAndId(userInfoDTO.getPlatform(), userInfoDTO.getOpenId());
        }
        if (ObjectUtils.isEmpty(currentUser)) {
            return null;
        }
        currentUser.setUpdateTime(new Date());
        currentUser.setEmail(userInfoDTO.getEmail());
        currentUser.setCountry(userInfoDTO.getCountry());
        currentUser.setCity(userInfoDTO.getCity());
        currentUser.setProvince(userInfoDTO.getProvince());
        currentUser.setGender(userInfoDTO.getGender());
        currentUser.setAvatarUrl(userInfoDTO.getAvatarUrl());
        currentUser.setNickname(userInfoDTO.getNickname());
        userInfoMapper.updateByPrimaryKeySelective(currentUser);
        return currentUser;
    }

    @Override
    public UserInfo updateUserAvatar(UserAvatarDTO avatarDTO) {
        log.info("开始更新用户头像信息");
        UserInfo currentUser = userInfoMapper.selectByPrimaryKey(avatarDTO.getId());
        if (ObjectUtils.isEmpty(currentUser)) {
            return null;
        }
        currentUser.setAvatarUrl(avatarDTO.getAvatarUrl());
        userInfoMapper.updateByPrimaryKeySelective(currentUser);
        return currentUser;
    }

    @Override
    public UserInfo getUserInfoById(String id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public UserInfo parseToken(String token, String platform) {
        try {
            // 解析并验证Token
            Claims claims = JwtUtils.parseToken(token.substring(7));
            OperatingUser operatingUser = new OperatingUser(claims.get("openId", String.class), claims.get("unionId", String.class));
            UserInfo user = getUserByPlatformAndId(platform, operatingUser.getOpenId());
            if (ObjectUtils.isEmpty(user)) {
                throw new InvalidTokenException("用户不存在，请先注册");
            }
            operatingUser.setUserId(user.getId());
            CurrentContext.setCurrentOperatingUser(operatingUser);
            return user;
        } catch (ExpiredJwtException e) {
            throw new InvalidTokenException("登录已过期，请重新登录");
        } catch (UnsupportedJwtException e) {
            throw new InvalidTokenException("身份验证失败，请重新登录");
        } catch (MalformedJwtException e) {
            throw new InvalidTokenException("无效的登录凭证，请重新登录");
        } catch (IllegalArgumentException e) {
            throw new InvalidTokenException("未提供有效身份信息，请登录");
        }
    }
}
